package com.csun.cmny.provider.device.csun.sleep.minzheng;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;


/**
 * @author HX
 * @date 2021/4/14
 */
@Slf4j
@Component
public class MqttPushServiceImpl {


    private String url="tcp://58.49.165.187:1883";

    public void mqttBedPush(Object vo, String clientId, String topic) {

        try {
            // 创建客户端
            // 内存存储
            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient sampleClient = new MqttClient(url, clientId, persistence);
            // 创建链接参数
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 在重新启动和重新连接时记住状态
            connOpts.setCleanSession(false);
            // 进行连接
            //sampleClient.connect(getOptions());
            // 设置连接的用户名
            connOpts.setUserName("admin");
            connOpts.setPassword("admin".toCharArray());
            // 建立连接
            sampleClient.connect(connOpts);
            // 创建消息
            // 对不同的设备创建多个消息
            MqttMessage message = null;
            try {
                message = new MqttMessage("setr=11".getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 设置消息的服务质量
            message.setQos(1);

            //设置日期格式
            //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //JSONObject json = JSONUtil.parseObj(vo, false);
            JSONObject json =JSONObject.fromObject(vo);
            //放入mqtt server  转utf-8防止乱码
            message.setPayload(json.toString().getBytes("UTF-8"));

            System.out.println(topic);
            // 发布消息
            sampleClient.publish(topic, message);

            log.info("----上报的主题topic：----:[{}]", topic);
            log.info("----报文json：----:[{}]", json);
            log.info("----上报的数据message----:[{}]", message);

            // 断开连接
            sampleClient.disconnect();
            // 关闭客户端
            sampleClient.close();
        } catch (MqttException me) {
            log.info("reason:[{}]", me.getReasonCode());
            log.info("msg:[{}]", me.getMessage());
            log.info("loc:[{}]", me.getLocalizedMessage());
            log.info("cause:[{}]", me.getCause());
            log.info("excep:[{}]", me);
            me.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
